package tech.yozo.bamboo.ui.home;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.List;

import tech.yozo.bamboo.db.BookDbHelper;
import tech.yozo.bamboo.model.Ebook;

public class HomeViewModel extends ViewModel {

    private BookDbHelper bookDbHelper;
    private final MutableLiveData<List<Ebook>> mBooks;

    public HomeViewModel() {
        mBooks = new MutableLiveData<>();
    }

    public void init(Context context) {
        bookDbHelper = new BookDbHelper(context);
    }

    @Override
    protected void onCleared() {
        if (bookDbHelper != null) {
            bookDbHelper.close();
        }
        super.onCleared();
    }

    public LiveData<List<Ebook>> getBooks() {
        return mBooks;
    }

    public void loadBooks() {
        List<Ebook> ebooks = bookDbHelper.getAllBooks();
        mBooks.setValue(ebooks);
    }

    public void saveBook(Ebook ebook) {
        bookDbHelper.saveBook(ebook);
    }

    public void saveBooks(List<Ebook> ebooks) {
        bookDbHelper.saveBooks(ebooks);
    }
}